import { AGConnectUser, SignInResult, } from '@hw-agconnect/auth-ohos';
import '@hw-agconnect/auth-ohos';
import { PhoneAuthProvider, VerifyCodeSettingBuilder, VerifyCodeAction,EmailAuthProvider } from '@hw-agconnect/auth-ohos';
import { AGCApi } from '@hw-agconnect/api-ohos';

import { Log } from '../common/Log';
import { getAGConnect } from './AgcConfig';
import DatabaseHelper from './DatabaseHelper';
import { AppStorageKit } from '../common/AppStorageKit';

const TAG = "[AGCAuth]";

export class AGCAuth {
  agc: AGCApi;
  context;

  // 初始化agc对象
  constructor(context) {
    this.context = context;
    this.agc = getAGConnect(context);
  }

  // 获取当前登录的用户信息
  public async getCurrentUser(): Promise<AGConnectUser> {
    return await this.agc.auth().getCurrentUser();
  }

  // 获取手机验证码
  public async requestPhoneVerifyCode(phone: string, ctrCode: string = '+86') {
    try {
      let verifyCodeSettings = new VerifyCodeSettingBuilder()
        .setAction(1001) // 1001表示注册登录，1002表示修改密码
        .setLang('zh_CN')
        .setSendInterval(300)
        .build();

      let ret = await this.agc.auth().requestPhoneVerifyCode(
        ctrCode,
        phone,
        verifyCodeSettings);

      return '验证码获取成功';
    } catch (err) {
      return '验证码获取失败:' + JSON.stringify(err);
    }
  }

  // 获取邮箱验证码
  public async requestEmailVerifyCode(email: string) {
    try {
      let verifyCodeSettings = new VerifyCodeSettingBuilder()
        .setAction(1001) // 1001表示注册登录，1002表示修改密码
        .setLang('zh_CN')
        .setSendInterval(300)
        .build();

      let ret = await this.agc.auth().requestEmailVerifyCode(
        email,
        verifyCodeSettings);

      return '验证码获取成功';
    } catch (err) {
      return '验证码获取失败:' + JSON.stringify(err);
    }
  }

  // 获取用户头像
  async getImg(uid) {
    const headImgs = await DatabaseHelper.userHeadImg_Query_By_uid(uid);
    if(headImgs && headImgs.length>0){
      return headImgs[0].imgurl;
    }else{
      return 'https://agc-storage-drcn.platform.dbankcloud.cn/v0/hmqa-bbnx2/user_dark.png?token=74d1ae76-2075-4ab2-b702-74ee968eb6ed';
    }
  }

  public async Change(user:AGConnectUser){
    let imgurl = await this.getImg(user.getUid());

    let userExtra = await user.getUserExtra();

    let loginRes = new AgUser(
      user.getUid(),
      imgurl,
      user.getPhone(),
      user.getEmail(),
      user.getDisplayName(),
      userExtra.getCreateTime(),
      userExtra.getLastSignInTime());

    return loginRes;
  }

  // 手机验证码登录
  public async login(isPhonelogin:boolean,username: string, verifyCode: string, countryCode: string = '+86'): Promise<AgUser> {
    return new Promise((resolve, reject) => {
      let credential = null;
      if(isPhonelogin){
        credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, username, verifyCode);
      }else{
        credential = EmailAuthProvider.credentialWithVerifyCode(username,verifyCode);
      }
      this.agc.auth().signIn(credential).then(async (ret) => {
        // @ts-ignore
        let user = ret.getUser();
        if (!user || user.getUid() === '') {
          reject({ message: '验证码错误' });
          return;
        }
        // 用户头像
        let loginRes = await this.Change(user)
        AppStorageKit.SetLoginUser<AgUser>(loginRes,this.context);

        resolve(loginRes);
      }).catch((error) => {
        reject(error);
      });
    });
  }

  public async logout(): Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      this.agc.auth().signOut().then(() => {
        resolve(true);
      }).catch((error) => {
        reject(error);
      });
    });
  }

  public async deleteUser(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.agc.auth().deleteUser().then(() => {
        resolve(true);
      }).catch((error) => {
        reject(error);
      });
    });
  }
}

export class AgUser {
  uid: String;
  photoUrl: String;
  phone: String;
  email: String;
  displayName: String;
  registerDate: String;
  lastLogin: String;

  constructor(uid: String = "", photoUrl: String = "", phone: String = "", email: String = "", displayName: String = "", registerDate: String = "", lastLogin: String = "") {
    this.uid = uid;
    this.photoUrl = photoUrl;
    this.phone = phone;
    this.email = email
    this.displayName = displayName;
    this.registerDate = registerDate;
    this.lastLogin = lastLogin;
  }

  getUid(): String {
    return this.uid;
  }

  getPhone(): String {
    return this.phone;
  }

  getEmail(): String {
    return this.email;
  }

  getDisplayName(): String {
    return this.displayName;
  }

  getPhotoUrl(): String {
    return this.photoUrl;
  }

  getRegisterDate(): String {
    return this.registerDate;
  }

  getLastLogin(): String {
    return this.lastLogin;
  }
}
